
package cn.javaxc.mvcwork.framework.servlets.url;
import cn.javaxc.mvcwork.controller.AuthenticationItem;
import cn.javaxc.mvcwork.framework.actions.TActionContext;
import cn.javaxc.mvcwork.framework.database.ConnectionElement;
import cn.javaxc.mvcwork.framework.servlets.url.base.URLMap;
import cn.javaxc.mvcwork.util.common.DatabaseUtils;
import java.io.IOException;
import java.sql.Connection;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
//import net.sf.asterisk.fastagi.DefaultAGIServer;








public class URLServlet extends HttpServlet {
  private static final long serialVersionUID = 2509011996512101242L;
  private Hashtable connectionElements = new Hashtable();
  public void doGet(TActionContext context)
      throws Exception {
    HttpServletRequest request = context.getRequest();
    HttpServletResponse response = context.getResponse();
    URLMap urlMap = new URLMap();
    
    String[] urlAttrs = request.getPathInfo().split("/");

    String returnURL = "";
    Connection db = null;
    try {
      ConnectionElement ce =retrieveConnectionElement(context);
      db = DatabaseUtils.getConnection(ce.getUrl(), ce.getUsername(), ce.getPassword());
      urlMap.queryRecord(db, Integer.parseInt(urlAttrs[urlAttrs.length-1]));

      if (Long.parseLong(urlAttrs[urlAttrs.length-2]) == urlMap.getTimeInMillis()){
        returnURL += urlMap.getUrl();        
      }
    } catch (Exception e) {
      e.printStackTrace();
    }finally{
      if (db != null ) {
        db.close();
      }
      db = null;
    }
    response.sendRedirect(returnURL);
  }
  protected synchronized ConnectionElement retrieveConnectionElement(TActionContext context) {
    String serverName = context.getRequest().getServerName();
    if (!connectionElements.containsKey(serverName)) {
      System.out.println("DefaultServlet-> Initializing Connection Element");
      AuthenticationItem auth = new AuthenticationItem();
      try {
        ConnectionElement ce = auth.getConnectionElement(context);
        connectionElements.put(serverName, ce);
      } catch (java.sql.SQLException e) {
        e.printStackTrace(System.out);
      }
    }
    return (ConnectionElement) connectionElements.get(serverName);
  }
}
